package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ReadMapper;
import com.heima.behavior.service.ReadService;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ReadServiceImpl extends ServiceImpl<ReadMapper, ApReadBehavior> implements ReadService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        ApReadBehavior one = getOne(Wrappers.<ApReadBehavior>lambdaQuery().eq(ApReadBehavior::getArticleId, dto.getArticleId()));
        Integer count = 1;
        if (one == null) {
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setEntryId(user.getId());
            apReadBehavior.setReadDuration(dto.getReadDuration());
            apReadBehavior.setPercentage(dto.getPercentage());
            apReadBehavior.setLoadDuration((int) dto.getLoadDuration());
            apReadBehavior.setCount(1);
            save(apReadBehavior);
        } else {
            count = one.getCount();
            one.setUpdateTime(new Date());
            one.setCount(++count);
            updateById(one);
            cacheService.lRightPop(user.getId() + "read" + dto.getArticleId());
        }
        cacheService.lLeftPush(user.getId() + "read" + dto.getArticleId(), +count + "");

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
